//
//  UserAccountViewModel.swift
//  8.31-WH微博
//
//  Created by 吴涵 on 15/9/9.
//  Copyright © 2015年 wuhan. All rights reserved.
//

import UIKit
import ReactiveCocoa
class UserAccountViewModel: NSObject {
    
    //单例
   static let sharedUserAccount = UserAccountViewModel()
    override init() {
        userAccount = UserAccount.loadUserAccount()
    }

    var userLogin : Bool {
    return accessToken != nil
    }
    var userAccount: UserAccount?
    
    var accessToken: String? {
    return userAccount?.access_token
    }
    var avatarUrl: NSURL? {
        
        return NSURL(string: userAccount?.avatar_large ?? "")
    
    }
    func loadUserAccount(code: String) -> RACSignal {
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            WHWebTools.sharedTools.loadAccessToken(code).doNext({ (result) -> Void in
                let  account = UserAccount(dict: result as! [String: AnyObject])
                
                self.userAccount = account
                printLog(account)
                
                WHWebTools.sharedTools.loadUserInfo(account.uid!).subscribeNext({ (result) -> Void in
                    let dict = result as! [String: AnyObject]
                    account.name = dict["name"] as? String
                    account.avatar_large = dict["avatar_large"] as? String
                    printLog(account)
                    account.saveUserAccount()
                    subscriber.sendCompleted()
                    }, error: { (error) -> Void in
                        
                        subscriber.sendError(error)
                })
                
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })
            
            return nil
        })
    
    }


}
